/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.fund.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.fund.domain.FundSource;
import me.zhengjie.modules.fund.repository.FundSourceRepository;
import me.zhengjie.modules.fund.service.FundSourceService;
import me.zhengjie.modules.fund.service.dto.FundSourceDto;
import me.zhengjie.modules.fund.service.dto.FundSourceQueryCriteria;
import me.zhengjie.modules.fund.service.mapstruct.FundSourceMapper;
import me.zhengjie.utils.*;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author Zheng Jie
 * @date 2019-04-10
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class FundSourceServiceImpl implements FundSourceService {

    private final FundSourceRepository fundSourceRepository;
    private final FundSourceMapper fundSourceMapper;
    private final RedisUtils redisUtils;

    @Override
    public Map<String, Object> queryAll(FundSourceQueryCriteria dict, Pageable pageable) {
        Page<FundSource> page = fundSourceRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable);
        return PageUtil.toPage(page.map(fundSourceMapper::toDto));
    }

    @Override
    public List<FundSourceDto> queryAll(FundSourceQueryCriteria fundSourceQueryCriteria) {
        List<FundSource> list = fundSourceRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, fundSourceQueryCriteria, cb));
        return fundSourceMapper.toDto(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(FundSource resources) {
        fundSourceRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(FundSource resources) {
        // 清理缓存
        delCaches(resources);
        FundSource fundSource = fundSourceRepository.findById(resources.getId()).orElseGet(FundSource::new);
        ValidationUtil.isNull(fundSource.getId(), "FundSource", "id", resources.getId());
        resources.setId(fundSource.getId());
        fundSourceRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        // 清理缓存
        List<FundSource> fundSourceList = fundSourceRepository.findByIdIn(ids);
        for (FundSource fundSource : fundSourceList) {
            delCaches(fundSource);
        }
        fundSourceRepository.deleteByIdIn(ids);
    }

    @Override
    public void download(List<FundSourceDto> fundSourceDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FundSourceDto fundSourceDto : fundSourceDtos) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("爬取地址", fundSourceDto.getFundUrl());
            map.put("基金代码", fundSourceDto.getFundCode());
            map.put("基金名称", fundSourceDto.getFundName());
            map.put("创建时间", fundSourceDto.getCreateTime());
            map.put("更新时间", fundSourceDto.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public void delCaches(FundSource fundSource) {
        redisUtils.del("fundSource::fundName:" + fundSource.getFundName());
    }
}